<template>
  <transition name="dialog-fade" @after-enter="afterEnter" @after-leave="afterLeave">
    <div v-show="visible" class="el-dialog__wrapper" @click.self="handleWrapperClick">
      <div role="dialog" :key="key" aria-modal="true" :aria-label="title || 'dialog'" :style="style" ref="dialog"
        :class="['el-dialog', { 'is-fullscreen': fullscreen, 'el-dialog--center': center }, customClass]" >
        <div class="el-dialog__header" :style="headerStyle">
          <slot name="title">
            <span class="el-dialog__title">{{ title }}</span>
          </slot>
          <button type="button" class="el-dialog__headerbtn" aria-label="Close" v-if="showClose" @click="handleClose">
            <i class="el-dialog__close el-icon el-icon-close"></i>
          </button>
        </div>
        <div class="el-dialog__body" v-if="rendered">
          <slot></slot>
        </div>
        <div class="el-dialog__footer" v-if="$slots.footer">
          <slot name="footer"></slot>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
  import Popup from 'element-ui/src/utils/popup';
  import Migrating from 'element-ui/src/mixins/migrating';
  import emitter from 'element-ui/src/mixins/emitter';
  import {
    hexToRGB
  } from '@/utils/cssUtil'

  export default {
    name: 'LamDialog',

    mixins: [Popup, emitter, Migrating],

    props: {
      title: {
        type: String,
        default: ''
      },

      modal: {
        type: Boolean,
        default: true
      },

      modalAppendToBody: {
        type: Boolean,
        default: true
      },

      appendToBody: {
        type: Boolean,
        default: false
      },

      lockScroll: {
        type: Boolean,
        default: true
      },

      closeOnClickModal: {
        type: Boolean,
        default: false
      },

      closeOnPressEscape: {
        type: Boolean,
        default: true
      },

      showClose: {
        type: Boolean,
        default: true
      },

      width: String,

      fullscreen: Boolean,

      customClass: {
        type: String,
        default: ''
      },

      top: {
        type: String,
        default: '15vh'
      },
      beforeClose: Function,
      center: {
        type: Boolean,
        default: false
      },

      draggable:{
        type: Boolean,
        default: true
      },

      widthResize:{
        type: Boolean,
        default: true
      },

      minWidth:{
        type: String,
        default: '315px'
      },

      destroyOnClose: Boolean
    },

    data() {
      return {
        closed: false,
        key: 0
      };
    },

    watch: {
      visible(val) {
        if (val) {
          this.closed = false;
          this.$emit('open');
          this.$el.addEventListener('scroll', this.updatePopper);
          this.$nextTick(() => {
            this.$refs.dialog.scrollTop = 0;
          });
          if (this.appendToBody) {
            document.body.appendChild(this.$el);
          }
        } else {
          this.$el.removeEventListener('scroll', this.updatePopper);
          if (!this.closed) this.$emit('close');
          if (this.destroyOnClose) {
            this.$nextTick(() => {
              this.key++;
            });
          }
        }
      }
    },

    computed: {
      style() {
        let style = {};
        if (!this.fullscreen) {
          style.marginTop = this.top;
          if (this.width) {
            style.width = this.width;
          }
        }
        return style;
      },
      headerStyle() {
        return {
          'padding': '10px 16px',
          'background-color': hexToRGB(this.$store.state.settings.theme, 25)
        }
      }
    },
    methods: {
      getMigratingConfig() {
        return {
          props: {
            'size': 'size is removed.'
          }
        };
      },
      handleWrapperClick() {
        if (!this.closeOnClickModal) return;
        this.handleClose();
      },
      handleClose() {
        if (typeof this.beforeClose === 'function') {
          this.beforeClose(this.hide);
        } else {
          this.hide();
        }
      },
      hide(cancel) {
        if (cancel !== false) {
          this.$emit('update:visible', false);
          this.$emit('close');
          this.closed = true;
        }
      },
      updatePopper() {
        this.broadcast('ElSelectDropdown', 'updatePopper');
        this.broadcast('ElDropdownMenu', 'updatePopper');
      },
      afterEnter() {
        this.$emit('opened');
      },
      afterLeave() {
        this.$emit('closed');
      }
    },

    mounted() {
      if (this.visible) {
        this.rendered = true;
        this.open();
        if (this.appendToBody) {
          document.body.appendChild(this.$el);
        }
      }

      //拖拽效果
      if(this.draggable){
        // 获取拖拽内容头部
        const dialogHeaderDom = this.$el.querySelector('.el-dialog__header');
        const dialogDom = this.$el.querySelector('.el-dialog');
        // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
        dialogDom.style.position = 'absolute';
        if(dialogDom.style.marginTop){
          if (dialogDom.style.marginTop.indexOf('vh')>-1) {
            dialogDom.style.top = document.body.clientHeight * (parseInt(dialogDom.style.marginTop.replace(/vh/g, ''))||0) / 100 + 'px';
          }else{
            dialogDom.style.top = dialogDom.style.marginTop
          }
        }else{
          dialogDom.style.top = "0px";
        }
        dialogDom.style.marginTop = 0;
        let width = dialogDom.style.width;
        if (width.indexOf('%')>-1) {
          width = document.body.clientWidth * parseInt(width.replace(/\%/g, '')) / 100;
        } else {
          width = width.replace(/\px/g, '');
        }
        dialogDom.style.left = `${(document.body.clientWidth - width) / 2}px`;

        const yMax = document.body.clientHeight - 44;

        // 鼠标按下事件
        dialogHeaderDom.addEventListener('mousedown', (e) => {
        // dialogHeaderDom.onmousedown = (e) => {
          let width = dialogDom.style.width;
          if (width.indexOf('%')>-1) {
            width = document.body.clientWidth * parseInt(width.replace(/\%/g, '')) / 100;
          } else {
            width = width.replace(/\px/g, '');
          }
          const xMax = document.body.clientWidth - width - 17;
          // 鼠标按下，计算当前元素距离可视区的距离 (鼠标点击位置距离可视窗口的距离)
          const startX = e.clientX;
          const startY = e.clientY;
          const startLeft = parseInt(dialogDom.style.left.replace(/\px/g, ''));
          const startTop = parseInt(dialogDom.style.top.replace(/\px/g, ''))||0;

          // 鼠标拖拽事件
          document.onmousemove = function (e) {
            dialogHeaderDom.style.cursor = 'move';
            // 计算移动的距离 （开始拖拽至结束拖拽的距离）
            let curLeft = e.clientX - startX + startLeft;
            let curTop = e.clientY - startY + startTop;
            curLeft = curLeft > xMax ? xMax : (curLeft < 0 ? 0 : curLeft);
            curTop = curTop > yMax ? yMax : (curTop < 0 ? 0 : curTop);
            dialogDom.style.left = curLeft + 'px';
            dialogDom.style.top = curTop + 'px';
          };

          document.onmouseup = function (e) {
            dialogHeaderDom.style.cursor = 'default';
            document.onmousemove = null;
            document.onmouseup = null;
          };
        });
      }

      //宽度可调整
      if(this.widthResize){
        const dragDom = this.$el.querySelector('.el-dialog');
        const minWidth = parseInt(this.minWidth.replace(/\px/g, ''))||0;
        const thatEl = this.$el;
        const lineEl = document.createElement('div');
        lineEl.style = 'width: 4px; background-color: rgb(228 228 228); border-bottom-right-radius: 8px; height: calc( 100% - 48px ); position: absolute; right: 0; bottom: 4px; margin: 0; z-index: 1; cursor: w-resize;';
        lineEl.addEventListener('mousedown', function (e) {
            // 计算当前元素距离可视区的距离
            const startX = e.clientX - thatEl.offsetLeft;
            const xMax = document.body.clientWidth - 17;
            // 当前宽度
            const curWidth = dragDom.offsetWidth;
            document.onmousemove = function (e) {
                e.preventDefault(); // 移动时禁用默认事件
                let newWidth = curWidth + e.clientX - startX;
                newWidth = newWidth < minWidth?minWidth:newWidth;
                newWidth = newWidth > xMax ? xMax : newWidth
                dragDom.style.width = `${newWidth}px`;
            };
            document.onmouseup = function (e) {
                document.onmousemove = null;
                document.onmouseup = null;
            };
        }, false);
        dragDom.appendChild(lineEl);
      }
    },

    destroyed() {
      // if appendToBody is true, remove DOM node after destroy
      if (this.appendToBody && this.$el && this.$el.parentNode) {
        this.$el.parentNode.removeChild(this.$el);
      }
    }
  };
</script>
